/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  LeaderErrorAssignActivity.java   
 * @Package com.jiyi.activity.leader   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-10-9 下午3:27:17   
 * @version V1.0     
 */
package com.jiyi.activity.leader;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jiyi.adapter.CommonAdapter;
import com.jiyi.adapter.ViewHolder;
import com.jiyi.bean.weibao.DistributePersonBean;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.UserHelp;
import com.jiyi.event.ErrorTaskListEvent;
import com.jiyi.inteface.WebApi;
import com.jiyi.view.DateChooseDialog;
import com.jiyi.widget.DropEditText;
import com.swift.base.ActivityBase;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.CheckUtil;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ClassName: LeaderErrorAssignActivity
 * @Description:TODO(系统错误派发)
 * @author: HYM
 * @date: 2017-10-9 下午3:27:17
 * 
 */
public class LeaderErrorTaskAssignActivity extends ActivityBase {

	/* 头部 */
	@BindView(R.id.tvBack)
	TextView tvBack;
	@BindView(R.id.tvTitle)
	TextView tvTitle;
	@BindView(R.id.tvSearch)
	TextView tvSearch;

	@BindView(R.id.tvCompany)
	TextView tvCompany;
	@BindView(R.id.et_start)
	EditText et_start;
	@BindView(R.id.det_repairer)
	DropEditText det_repairer;
	@BindView(R.id.et_remark)
	EditText et_remark;
	
	CommonAdapter<DistributePersonBean> distributerAdapter;
	CommonAdapter<DistributePersonBean> distributerAutoAdapter;
	private List<DistributePersonBean> distributer_list = new ArrayList<DistributePersonBean>();
	private List<DistributePersonBean> distributer_auto = new ArrayList<DistributePersonBean>();

	Dialog dialog;
	String cfid,owner_id,owner_name;
	int position;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_leader_error_task_assign);
		ButterKnife.bind(this);
		init();
	}

	private void init() {
		getIntentData();
		setTop();
		setViewState();
		setAdater();
		getRepairerData("");
	}
	
	private void getIntentData() {
		cfid = getIntent().getStringExtra("cfid");
		owner_id = getIntent().getStringExtra("owner_id");
		position = getIntent().getIntExtra("position", 0);
		owner_name = getIntent().getStringExtra("owner_name");
	}

	private void setViewState() {
		et_start.setTag(R.id.tag_view_empty, "开始时间不能为空");
		et_start.setKeyListener(null);
		et_start.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				DateChooseDialog.Builder builder = new DateChooseDialog.Builder(
						v.getContext());
				builder.setTitle("选择日期");
				builder.setTextView(et_start);
				builder.setPositiveButton("确定",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
							}
						});

				builder.setNegativeButton("取消",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
							}
						});
				builder.create().show();
			}
		});

		det_repairer.setTag(R.id.tag_view_empty, "派发对象不能为空");
		
		tvCompany.setText(owner_name);
	}

	void setTop()
	{
		tvTitle.setText("系统报错派发");
		tvSearch.setVisibility(View.GONE);
	}
	
	private void setAdater() {
		distributerAdapter = new CommonAdapter<DistributePersonBean>(context,
				distributer_list, R.layout.item_equipment_repair_state) {

			@Override
			public void convert(ViewHolder holder, DistributePersonBean t) {
				holder.setText(R.id.state_name, t.getName());
			}
		};
		distributerAutoAdapter = new CommonAdapter<DistributePersonBean>(
				context, distributer_auto, R.layout.item_equipment_repair_state) {

			@Override
			public void convert(ViewHolder holder, final DistributePersonBean t) {
				holder.setText(R.id.state_name, t.getName());
				holder.setOnClickListener(R.id.state_name,
						new OnClickListener() {

							@Override
							public void onClick(View v) {
								det_repairer.doItemClick(t.getName(), t.getId());
							}
						});
			}
		};

		det_repairer.setOnItemClick(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				DistributePersonBean distributePersonBean = (DistributePersonBean) parent
						.getAdapter().getItem(position);
				det_repairer.doListItemClick(distributePersonBean.getName(),
						distributePersonBean.getId());
			}
		});
		det_repairer.setAdapter(distributerAutoAdapter);
		det_repairer.setListAdapter(distributerAdapter);
		det_repairer.setHandler(repairerHandler);
	}
	
	Handler repairerHandler = new Handler() {
		public void dispatchMessage(android.os.Message msg) {
			switch (msg.what) {
			case AppConfig.DET_RELOAD:
				getRepairerData(det_repairer.getText().toString());
				break;

			default:
				break;
			}
		};
	};
	
	private void getRepairerData(String keyword) {

		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		if (!TextUtils.isEmpty(keyword)) {
			params.put("keyword", keyword);
		}

		VolleyRequest.StringRequestPost(context,
				WebApi.MAINTENANCE_LEADER_REPAIRER_LIST, "", params,
				new StringInterface(context) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								String data = obj.getString("data");
								List<DistributePersonBean> temp = new Gson()
										.fromJson(
												data,
												new TypeToken<List<DistributePersonBean>>() {
												}.getType());
								// 填充数据
								distributer_list.clear();
								distributer_list.addAll(temp);
								distributerAdapter.notifyDataSetChanged();
								distributer_auto.clear();
								distributer_auto.addAll(temp);
								distributerAutoAdapter.notifyDataSetChanged();
								det_repairer.isLoadData = true;
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
						}
					}

					@Override
					public void stringError(VolleyError error) {
					}
				});

	}
	
	void doPost() {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		params.put("company_id", owner_id);
		params.put("expect_date", et_start.getText().toString());
		params.put("rid", det_repairer.getSelectedId());
		params.put("zg_comments", et_remark.getText().toString());
		params.put("cfid", cfid);

		dialog = showDialog(dialog);
		VolleyRequest.StringRequestPost(this, WebApi.MAINTENANCE_LEADER_ERROR_TASK_LIST_ASSIGN,
				"", params, new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								ToastUtil.getInstances().showMsg(info);
								EventBus.getDefault().post(
										new ErrorTaskListEvent(2, position,
												2));
								finish();
							} 
							else if (status.equals("404") && info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg("尚未登录或该用户在其他地方登录，请重新登录！");
								//清除环信登录
								UserHelp.getInstance().clearUser(AppBase.Context, true);
								return;
							}
							else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							hideDialog(dialog);
						}
					}

					@Override
					public void stringError(VolleyError error) {
						hideDialog(dialog);
						ToastUtil.getInstances().showMsg("派发失败");
					}
				});
	}
	
	@OnClick({ R.id.tvBack,R.id.tvAssign })
	public void onClick(View view) {
		Intent intent = null;
		switch (view.getId()) {
		case R.id.tvBack:
			finish();
			break;
		case R.id.tvAssign:
			if(CheckUtil.checkView(et_start, det_repairer))
			{
				doPost();
			}
			break;
		default:
			break;
		}
	}
}
